import { useState, useEffect, useRef } from 'react';
import { Form, Input, Button, message, Modal, Space } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { connect, FormattedMessage, useIntl } from 'umi';
import { DeptSelect } from '@/components/FormItemSelect';
import request from '@/utils/request';

const currControl = 'Employee';
const apiURL = '/api/services/app/Employee/';
const { confirm } = Modal;

const EmpEdit = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [datas, setDatas] = useState<any>({});
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    const { ParentData } = props;
    if (ParentData && ParentData.id) {
      getData(ParentData.id);
    }
  }, [props.ParentData]);

  const getData = (id: number) => {
    if (id) {
      request(apiURL + 'Get', {
        method: 'GET',
        params: { id },
      }).then((response) => {
        if (response) {
          if (response.success) {
            const result = response.result;
            formRef.current.setFieldsValue({ model: result });
            setDatas(result);
          }
          setLoading(false);
        }
      });
    }
  };

  const onFinish = async (values: any) => {
    let act = 'Abp/newObj';
    if (values.model.id) {
      act = 'Abp/modify';
    }
    values.model.userId = props.currentUser.id;
    props
      .dispatch({
        type: act,
        payload: values.model,
        control: currControl,
      })
      .then(() => {
        const resp = props.response;
        if (resp.success) {
          message.success(intl.formatMessage({id:'pages.save.success'}));
          props.fetchDatas();
        } else {
          message.error(intl.formatMessage({id:'pages.save.failed'}));
        }
      });
  };

  const ResetForm = () => {
    const data = {
      id: 0,
    };
    setDatas(data);
    formRef.current.resetFields();
  };

  const handleDel = () => {
    props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: datas.id },
        control: currControl,
      })
      .then(() => {
        const resp = props.response;
        if (resp.success) {
          message.success(intl.formatMessage({id:'pages.delete.success'}));
          props.fetchDatas();
          formRef.current.resetFields();
        } else {
          message.error(intl.formatMessage({id:'pages.delete.failed'}));
        }
      });
  };

  const showConfirm = () => {
    confirm({
      title: intl.formatMessage({id:'pages.warning'}),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({id:'pages.delete.confirm'}),
      onOk() {
        handleDel();
      },
      onCancel() {},
    });
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 },
  };

  return (
    <div>
      <Form {...layout} ref={formRef} onFinish={onFinish}>
        <Form.Item hidden label="id" name={['model', 'id']}>
          <Input />
        </Form.Item>
        <DeptSelect
          width={200}
          idValue
          name={['model', 'deptId']}
          placeholder={<FormattedMessage id="pages.select.department" />}
          label={<FormattedMessage id="pages.superiorDepartment" />}
        />
        <Form.Item
          name={['model', 'empName']}
          label={<FormattedMessage id="pages.empName" />}
          rules={[{ required: true, message: intl.formatMessage({id:'pages.empName.required'}) }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name={['model', 'empNum']}
          label={<FormattedMessage id="pages.empNum" />}
          rules={[{ required: true, message: intl.formatMessage({id:'pages.empNum.required'}) }]}
        >
          <Input />
        </Form.Item>
        <Form.Item name={['model', 'email']} label={<FormattedMessage id="pages.email" />}>
          <Input />
        </Form.Item>
        <Form.Item name={['model', 'phone']} label={<FormattedMessage id="pages.telphone" />}>
          <Input />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: layout.labelCol.span }}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              <FormattedMessage id="pages.save" />
            </Button>
            <Button onClick={ResetForm}>
              <FormattedMessage id="pages.reset" />
            </Button>
            <Button danger onClick={showConfirm} disabled={!datas.id}>
              <FormattedMessage id="pages.delete" />
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(EmpEdit);
